#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unistd.h>
#include <pthread.h>

using func_t = std::function<void(std::string)>;

namespace ThreadModule
{
    class Thread
    {
    public:
        Thread(func_t func, const std::string &name = "thread")
            : _tid(-1), _threadName(name), _func(func), _isrunning(false)
        {
        }
        static void *threadrun(void *args)
        {
            Thread *td = reinterpret_cast<Thread*>(args);
            td->_func(td->_threadName);
            return nullptr;
        }
        bool Start()
        {
            int n = pthread_create(&_tid, nullptr, threadrun, this);
            if (n == 0)
            {
                _isrunning = true;
                return true;
            }
            else
            {
                return false;
            }
        }
        void Join()
        {
            if (_isrunning)
            {
                pthread_join(_tid, nullptr);
            }
        }
        void Detach()
        {
            if (_isrunning)
            {
                pthread_detach(_tid);
            }
        }
        std::string name()
        {
            return _threadName;
        }
        void Stop()
        {
            _isrunning = false;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _threadName;
        func_t _func;
        bool _isrunning;
    };
}